<template>
  <Form ref="treeNodeForm" :model="modelForm" :rules="rules" label-position="right" :label-width="90">
    <div>
      <Row :gutter="32" class="code-row-bg">
        <Col span="11">
          <Form-item
            :label="comp === 'orgManage' ? '父组织名称' : '上级关键业务环节名称'"
            :label-width="160"
            v-if="!isRoot"
          >
            <Input placeholder="请输入" v-model.trim="modelForm.parentOrgName" :maxlength="50" :disabled="true"></Input>
          </Form-item>
        </Col>
        <Col span="11">
          <Form-item
            :label="comp === 'orgManage' ? '父组织编码' : '上级关键业务环节编码'"
            :label-width="160"
            v-if="!isRoot"
          >
            <Input placeholder="请输入" v-model.trim="modelForm.parentOrgCode" :maxlength="50" :disabled="true"></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="11">
          <Form-item prop="orgName" :label="comp === 'orgManage' ? '组织名称' : '关键业务环节名称'" :label-width="150">
            <Input placeholder="请输入" v-model.trim="modelForm.orgName" :maxlength="50"></Input>
          </Form-item>
        </Col>
        <Col span="11">
          <Form-item prop="orgCode" :label="comp === 'orgManage' ? '组织编码' : '关键业务环节编码'" :label-width="150">
            <Input
              placeholder="请输入"
              v-model.trim="modelForm.orgCode"
              :maxlength="50"
              :disabled="!isAdd"
              @on-change="onChange"
            >
            </Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="22" style="margin-top: 15px;" class="code-row-bg tree-node-button">
        <Col span="20">
          <RPButton v-if="!isRoot" optType="save" style="margin-left: 80px;" :loading="saveLoading" @click="save" />
        </Col>
      </Row>
    </div>
    <div class="system" v-if="showSys">
      <InnerPageTable ref="valueSetTable" :config="pageTableConfig">
        <div slot="table-bar">
          <RPButton optType="create" type="button" text="关联系统" @click="handleCreate" />
          <RPButton optType="create" type="button" text="移除关联" @click="handleRemove" />
        </div>
      </InnerPageTable>
    </div>
  </Form>
</template>

<script>
import treeAPI from '@/api/treeApi.js'
import { systemColumn } from './columns'
import connectSys from '../keyBiz/connectSys.vue'
import delConnect from '../keyBiz/delConnect.vue'
export default {
  data() {
    const validateOrgName = (rule, value, callback) => {
      if (value == null || value === '' || value != value.trim()) {
        callback(new Error('请输入名称'))
      }
      callback()
    }
    const codeReg = '^([a-zA-Z0-9]|\\/|\\.|_|-|\\*|\\%)+$'
    const validateOrgCode = (rule, value, callback) => {
      if (value == null || value === '') {
        callback(new Error('请输入组织编码'))
      } else if (value.length > 30) {
        callback(new Error('请输入1~30个字符'))
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error('请输入字母、数字、下划线、中划线、/和.'))
      } else if (value.indexOf(' ') != -1) {
        callback(new Error('树编码中不能存在空格'))
      }
      callback()
    }
    return {
      modelForm: {
        orgName: '',
        orgCode: '',
        parentOrgCode: '',
        parentOrgName: ''
      },
      rules: {
        orgName: [{ validator: validateOrgName, trigger: 'blur', required: true }],
        orgCode: [{ validator: validateOrgCode, trigger: 'blur', required: true }]
      },
      saveLoading: false,
      isRoot: false,
      isAdd: false,
      selectedRowKeys: [],
      changed: false,
      // dealInfoConfig: {}
    }
  },
  props: {
    comp: {
      type: String,
      default: 'orgManage'
    },
    infoConfig: {
      type: Object,
      default: () => {}
    },
    addInfo: {
      type: Object,
      default: () => {}
    },
    dcPeriod: {
      type: String,
      default: ''
    }
  },
  computed: {
    showSys() {
      if (this.comp === 'keyBiz' && this.infoConfig.isLeaf) {
        return true
      }
      return false
    },
    pageTableConfig() {
      return {
        autoFirst: true,
        columns: systemColumn.bind(this)(),
        resource: JSON.parse(this.infoConfig.modelForm.ext1) || [],
        onSelectionChange: this.handleSelectionChange
      }
    }
  },
  methods: {
    onChange() {
      if (!this.modelForm.orgCode.startsWith(this.modelForm.parentOrgCode)) {
        this.modelForm.orgCode = this.modelForm.parentOrgCode + '001'
      }
    },
    addOrgNode(params) {
      return treeAPI.addTreeNode(params).then(data => {
        return data
      })
    },
    addSys(params) {
      return treeAPI.addKeyNode(params).then(data => {
        return data
      })
    },
    async save() {
      this.$refs['treeNodeForm'].validate(async valid => {
        if (valid) {
          // 添加
          const params = {
            parent: {
              id: this.addInfo.id,
              tenantCode: this.addInfo.tenantCode,
              nodeType: 'standard',
              nodeCode: this.addInfo.parentNodeCode,
              nodeName: this.addInfo.parentNodeName
            },
            node: {
              nodeType: 'standard',
              nodeName: this.modelForm.orgName,
              nodeCode: this.modelForm.orgCode,
              nodePath: this.addInfo.parentNodePath + '/' + this.modelForm.orgCode,
              parentId: this.addInfo.id,
              nodeLevel: 0,
              tenantCode: 'itshare-sit'
            },
            buCode: this.$store.state.userBu.key,
            dcPeriod: this.dcPeriod || this.$store.state.writeablePeriod,
            treeCode:
              this.comp === 'orgManage' ? 'ZZ-' + this.$store.state.userBu.key : 'GJ-' + this.$store.state.userBu.key,
            isFirst: this.addInfo.isFirst
          }
          if (this.isAdd) {
            const res = this.comp === 'orgManage' ? await this.addOrgNode(params) : await this.addSys(params)
            this.saveLoading = false
            if (res.data.code !== 200) {
              this.$message.error({
                content: res.data.msg,
                duration: 3
              })
              return
            }
            // this.modelForm.orgName = res.data.nodeName;
            // this.modelForm.orgCode = res.data.nodeCode;
            this.$emit('setAreaTitle', '组织信息')
            this.$message.success({
              content: '新建成功',
              duration: 3
            })
            this.$emit('close', true)
            this.$emit('infoChanged', true)
          } else {
            // 修改
            const params = {
              buCode: this.$store.state.userBu.key,
              dcPeriod: this.dcPeriod,
              treeCode:
                this.comp === 'orgManage' ? 'ZZ-' + this.$store.state.userBu.key : 'GJ-' + this.$store.state.userBu.key,
              ...this.infoConfig.modelForm
            }
            params.nodeName = this.modelForm.orgName
            treeAPI
              .updateTreeNode(params)
              .then(data => {
                if (data.code !== 200) {
                  this.$message.error({
                    content: data.msg,
                    duration: 3
                  })
                  return
                }
                this.saveLoading = false
                this.$message.success({
                  content: '修改成功',
                  duration: 3
                })
                this.$emit('setAreaTitle', '组织信息')
                this.$emit('close', true)
                this.$emit('infoChanged', true)
              })
              .catch(error => {
                this.saveLoading = false
              })
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.selectedRowKeys = val
    },
    handleCreate() {
      new this.$pageModal(
        connectSys,
        {
          props: {
            dcPeriod: this.dcPeriod,
            modelForm: this.infoConfig.modelForm,
            tenantCode: this.addInfo.tenantCode
          }
        },
        data => {
          if (data) {
            this.infoConfig.modelForm = data
            this.$emit("infoChanged", true)
          }
        }
      )
    },
    handleRemove() {
      if (this.selectedRowKeys.length) {
        new this.$pageModal(
          delConnect,
          {
            props: {
              dcPeriod: this.dcPeriod,
              modelForm: this.infoConfig.modelForm,
              selectedRowKeys: this.selectedRowKeys
            }
          },
          data => {
            if (data) {
              this.infoConfig.modelForm = data
              this.$emit('infoChanged', true)
            }
          }
        )
      }
    }
  },
  watch: {
    infoConfig: {
      handler(newVal) {
        this.isRoot = newVal.isRoot
        this.isAdd = false
        this.modelForm.orgName = newVal.modelForm.nodeName
        this.modelForm.orgCode = newVal.modelForm.nodeCode
        const nodeName = newVal.modelForm.nodeNamePath?.split('/')
        nodeName?.pop()
        this.modelForm.parentOrgName = nodeName?.pop()
        const nodePath = newVal.modelForm.nodePath?.split('/')
        nodePath?.pop()
        this.modelForm.parentOrgCode = nodePath?.pop()
      },
      deep: true
    },
    addInfo: {
      handler(newVal) {
        this.isAdd = true
        this.isRoot = false
        this.modelForm.orgName = ''
        this.modelForm.orgCode = newVal.parentNodeCode + '001'
        this.modelForm.parentOrgName = newVal.parentNodeName
        this.modelForm.parentOrgCode = newVal.parentNodeCode
      }
    }
  },
  // created() {
  //   this.dealInfoConfig = this.infoConfig
  // }
}
</script>

<style lang="less" scoped>
/deep/.ivu-row {
  margin: 20px 0;
}
.system {
  margin-top: 100px;
}
</style>
